﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;

namespace 动态为类型添加属性
{
    /// <summary>
    /// 自定义动态类基础动态基类
    /// </summary>
    public class DynamicModel : DynamicObject
    {
        private string propertyName;
        public string PropertyName
        {
            set
            {
                propertyName = value;
            }
            get
            {
                return propertyName;
            }
        }

        /// <summary>
        /// 属性字典
        /// </summary>
        private Dictionary<string, object> properties = new Dictionary<string, object>();

        /// <summary>
        /// 属性字典
        /// </summary>
        public Dictionary<string, object> Properties
        {
            get
            {
                return properties;
            }
        }

        /// <summary>
        /// 字典键值对个数
        /// </summary>
        public int Count
        {
            get
            {
                return properties.Count;
            }
        }

        /// <summary>
        /// 重写取值
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            string name = binder.Name;
            result = null;
            return Properties.TryGetValue(name, out result);
        }

        /// <summary>
        /// 重写设值
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (binder.Name == "Property")
            {
                Properties[propertyName] = value;
            }
            else
            {
                Properties[binder.Name] = value;
            }
            return true;
        }
    }
}
